#include "Connection.h"

bool Connection::ListTables(std::vector<TBInfo>& infos)
{
	infos.clear();

	const std::string _Sql = R"(
SHOW TABLES;
)";
	if (!Execute(_Sql))
	{
		return false;
	}

	MYSQL_RES* result = mysql_store_result(m_Conn);
	MYSQL_ROW row;
	while ((row = mysql_fetch_row(result)) != NULL) {
		TBInfo info;
		info.m_TableName= row[0];
		infos.emplace_back(info);
	}
	mysql_free_result(result);
	return true;
}
bool Connection::ListUsers(std::vector<UserInfo>& infos)
{
	infos.clear();

	const std::string _Sql = R"(
SELECT User, Host FROM mysql.user;
)";
	if (!Execute(_Sql))
	{
		return false;
	}

	MYSQL_RES* result = mysql_store_result(m_Conn);
	MYSQL_ROW row;
	while ((row = mysql_fetch_row(result)) != NULL) {
		UserInfo info;
		info.m_User = row[0];
		info.m_Host = row[1];
		infos.emplace_back(info);
	}
	mysql_free_result(result);
	return true;
}

bool Connection::ListDatabaseInfos(std::vector<DatabaseInfo>& dbs)
{

	dbs.clear();

	std::string _Sql = R"(
SHOW DATABASES;
)";

	if (!Execute(_Sql))
	{
		return false;
	}

	MYSQL_RES* result = mysql_store_result(m_Conn);
	MYSQL_ROW row;
	while ((row = mysql_fetch_row(result)) != NULL) {
		DatabaseInfo db;
		db.m_Id = row[0];
		dbs.emplace_back(db);
	}
	mysql_free_result(result);

	return true;
}

bool Connection::GetTableInfo(TBGetInfo& info)
{
	info.m_Fields.clear();

	if (!Execute(info.Sql()))
	{
		return false;
	}

	MYSQL_RES* result = mysql_store_result(m_Conn);
	MYSQL_ROW row;
	while ((row = mysql_fetch_row(result)) != NULL) {
		Field field;
		field.m_Name = row[0];
		field.SetColumType(row[1]);
		field.SetIsNullString(row[2]);
		field.SetColumKey(row[3]);
		field.SetDefaultSource(row[4]);
		field.SetExtra(row[5]);
		info.m_Fields.emplace_back(field);
	}
	mysql_free_result(result);

	return true;
}

bool Connection::UseDatabase(const std::string& dbName)
{
	std::string _Sql = R"(USE )";
	return Execute(_Sql + dbName);
}
